package com.it.park.controller.expose;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.it.park.client.service.AppVersionDownloadRecordService;
import com.it.park.client.service.AppVersionService;
import com.it.park.client.service.ArticleService;
import com.it.park.client.service.ArticleTypeService;
import com.it.park.client.service.BookService;
import com.it.park.client.service.HomeLogoService;
import com.it.park.client.service.LinkService;
import com.it.park.client.service.MomentsService;
import com.it.park.client.service.NoticeService;
import com.it.park.client.service.QuestionService;
import com.it.park.client.service.QuestionTypeService;
import com.it.park.client.service.ResouceFileService;
import com.it.park.client.service.SignService;
import com.it.park.client.service.VersionService;
import com.it.park.client.service.VisitInfoService;
import com.it.park.common.JsonObj;
import com.it.park.common.Page;
import com.it.park.constant.Constant;
import com.it.park.model.AppVersion;
import com.it.park.model.AppVersionDownloadRecord;
import com.it.park.model.Article;
import com.it.park.model.ArticleType;
import com.it.park.model.ArticleVo;
import com.it.park.model.Book;
import com.it.park.model.HomeLogo;
import com.it.park.model.Link;
import com.it.park.model.Moments;
import com.it.park.model.Notice;
import com.it.park.model.Question;
import com.it.park.model.QuestionType;
import com.it.park.model.ResourceFile;
import com.it.park.model.Sign;
import com.it.park.model.Version;
import com.it.park.model.VisitInfo;
import com.it.park.rms.client.model.User;
import com.it.park.rms.client.service.UserService;
import com.it.park.util.date.DateUtil;
import com.it.park.util.email.EmailUtil;
import com.it.park.util.image.ImageUtil;
import com.it.park.util.ip.IPUtil;

@Controller
public class IndexController {
	
	private static Log log = LogFactory.getLog(IndexController.class);
	private String rootPath=Constant.EXPOSE_PATH;
	
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private LinkService linkService;
	@Autowired
	private ArticleTypeService articleTypeService;
	@Autowired
	private ArticleService articleService;
	@Autowired
	private  VisitInfoService visitInfoService;
	@Autowired
	private ResouceFileService resouceFileService;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private QuestionTypeService questionTypeService;
	@Autowired
	private UserService userService;
	@Autowired
	private VersionService versionService;
	@Autowired
	private SignService signService;
	@Autowired
	private MomentsService momentsService;
	@Autowired
	private HomeLogoService homeLogoService;
	@Autowired
	private AppVersionService appVersionService;
	@Autowired
	private AppVersionDownloadRecordService appVersionDownloadRecordService;
	@Autowired
	private BookService bookService;
	
	private Page page = null;
	
	/**
	 * 首页
	 */
	@RequestMapping("index")
	public String index(HttpServletRequest request){
			//网站通知
			List<Notice> notices = noticeService.selectAll();
			request.setAttribute("notices", notices);
			
			//友情链接
			List<Link> links = linkService.selectAll();
			request.setAttribute("links", links);
			
			//标签类别
			List<ArticleType> articleTypes = articleTypeService.selectAll();
			request.setAttribute("articleTypes", articleTypes);
			
			List<ResourceFile> resourceFiles = resouceFileService.selectAll();
			request.setAttribute("resourceFiles", resourceFiles);
			
			Map<String,Object> map = new HashMap<String, Object>();
			//Web文章
			map.put("category", 1);
			List<Article> articleWeb = articleService.selectByCategoryType(map);
			request.setAttribute("articleWeb", articleWeb);
			//数据库文章
			map.put("category", 2);
			List<Article> articleDatabase = articleService.selectByCategoryType(map);
			request.setAttribute("articleDatabase", articleDatabase);
			//前端开发文章
			map.put("category", 3);
			List<Article> articleFront = articleService.selectByCategoryType(map);
			request.setAttribute("articleFront", articleFront);
			//服务器文章
			map.put("category", 4);
			List<Article> articleServer = articleService.selectByCategoryType(map);
			request.setAttribute("articleServer", articleServer);
			//云计算文章
			map.put("category", 5);
			List<Article> articleCloud = articleService.selectByCategoryType(map);
			request.setAttribute("articleCloud", articleCloud);
			//大数据文章
			map.put("category", 6);
			List<Article> articleHadoop = articleService.selectByCategoryType(map);
			request.setAttribute("articleHadoop", articleHadoop);
		
			//最热评论
			List<ResourceFile> hostCommentFiles = 	resouceFileService.selectHostCommentList();
			request.setAttribute("hostCommentFiles", hostCommentFiles);
			
//			//下载排行
//			List<ResourceFile> rFiles = 	resouceFileService.selectRankingList();
//			request.setAttribute("rFiles", rFiles);
			
			//大于当前时间15天注册的用户
			List<User> users = userService.selectLatestRegister();
			request.setAttribute("users", users);
			
			//积分排行
			List<User> userRanks = userService.selectIntegralRanking();
			request.setAttribute("userRanks", userRanks);
			
			//心情
			List<Sign> signs = signService.selectByLimit();
			request.setAttribute("signs", signs);
			
			//动态
			List<Moments> moments = momentsService.selectByLimit();
			request.setAttribute("moments", moments);
			
//			//首页图片新闻切换
			Integer type = 1;
			List<HomeLogo> news =  homeLogoService.selectShowImg(type);
			request.setAttribute("news", news);
			
			//首页最新评论文章
			List<ArticleVo> newArticels = articleService.selectNewArticleComment();
			request.setAttribute("newArticels", newArticels);
			
			//首页书籍显示
			List<Book> books =  bookService.selectByList();
			request.setAttribute("books", books);
			
			//获取访问者的IP
//			final String ip = IPUtil.getIP(request);
//			final String ip = "163.125.126.238";
//			log.info("访问者IP"+ip);
			
//			reordVisitor(ip);
			return rootPath+"index";
	}
	
	
	@RequestMapping("listLogos")
	@ResponseBody
	public List<HomeLogo>  listLogos(HttpServletResponse response){
		Integer type = 0;
		return homeLogoService.selectShowImg(type);
	}
	
	@RequestMapping("homeLogo")
	public void homeLogo(Integer id,HttpServletResponse response){
		HomeLogo hl = homeLogoService.selectByPrimaryKey(id);
		try {
			ImageUtil.showPicture(hl.getImgFile(), response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public  void reordVisitor(String ip){
		String  visitInfo = IPUtil.getAddressByIP(ip);
		if(visitInfo != "" && visitInfo != null){
			String[] datas = IPUtil.getDatas(visitInfo);
			if(datas != null && datas.length >0){
				String date = DateUtil.getDate();
				String day = date.substring(0, 10);
				String time = date.substring(11);
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("ip", ip);
				map.put("visitDate",day);
				VisitInfo v =  visitInfoService.selectByIPAndDate(map);
				if(v == null){
					v = new VisitInfo(datas[0],datas[1],datas[2],datas[3],datas[4],datas[5],datas[6],datas[7],datas[8],datas[9],datas[10],datas[11],ip,day,time);
					visitInfoService.insertSelective(v);
				}
			}else{
				log.error("获取地理位置失败");
			}
		}
	}
	
	/**
	 * 大于当前时间15天注册的用户
	 */
	@RequestMapping("showRegisterUser")
	public void showRegisterUser(){
		
	}
	
	/**
	 * 首页实时更新的文章内容
	 */
	@RequestMapping("listArticle")
	@ResponseBody
	public JsonObj listArticle(HttpServletRequest request){
		JsonObj jsonObj = new JsonObj();
		//文章
		List<Article> articles = articleService.selectAll();
		jsonObj.setObject(articles);
		jsonObj.setSuccess(true);
		
		return jsonObj;
	}
	
	/**
	 * 最热下载
	 */
	@RequestMapping("listResourceFile")
	@ResponseBody
	public JsonObj listResourceFile(){
		JsonObj jsonObj = new JsonObj();
		List<ResourceFile> resourceFiles = resouceFileService.selectRankingList();
		jsonObj.setObject(resourceFiles);
		jsonObj.setSuccess(true);
		return jsonObj;
	}
	
	@RequestMapping("list")
	public String list(HttpServletRequest request){
		return rootPath+"list";
	}
	
	/**
	 * 意见
	 */
	@RequestMapping("suggestion")
	public String suggestion(HttpServletRequest request){
		return rootPath+"suggestion";
	}
	
	
	/**
	 * 意见反馈，发送邮件
	 */
	@RequestMapping("sendEmail")
	@ResponseBody
	public JsonObj sendEmail(@RequestParam("email") String email,@RequestParam("content") String content,HttpServletRequest request){
		JsonObj jsonObj = new JsonObj();
		boolean success = EmailUtil.sendEmail(content);
		if(success){
			jsonObj.setMessage(Constant.EMAIL_SUC);
		}else{
			jsonObj.setMessage(Constant.EMAIL_FAIL);
			jsonObj.setSuccess(false);
		}
		return jsonObj;
	}
	
	/**
	 * 版本更新
	 */
	@RequestMapping("version")
	public String version(HttpServletRequest request){
		//PC版本
		List<Version> versions  = versionService.selectAll();
		request.setAttribute("versions", versions);
		//app版本
		AppVersion appVersion =  appVersionService.selectLatestVersion();
		request.setAttribute("appVersion", appVersion);
		Integer  totalDownCount = appVersionService.selectTotalDown();
		request.setAttribute("totalDownCount", totalDownCount);
		return rootPath+"version";
	}
	
	
	/**
	 * 交流问答
	 */
	@RequestMapping("question")
	public String question(HttpServletRequest request){
		String pageNow = request.getParameter("pageNow");
		Map<String,Object> map = new HashMap<String, Object>();
		Integer total = questionService.selectTotal(map);
		if(pageNow != null){
			page = new Page(Integer.parseInt(pageNow),total,10);
		}else{
			page = new Page(1,total,10);
		}
		map.put("startPos", page.getStartPos());
		map.put("pageSize", page.getPageSize());
		 List<Question> questions = questionService.selectPagination(map);
		request.setAttribute("page", page);
		request.setAttribute("questions", questions);
		 List<QuestionType> questionTypes = questionTypeService.selectAll();
		 request.setAttribute("questionTypes", questionTypes);
		return rootPath+"question";
	}
	
	
	/**
	 *更多资料，标签云出跳转
	 */
	@RequestMapping("spanMoreList")
	public String spanMoreList(HttpServletRequest request){
		List<ArticleType> articleTypes = articleTypeService.selectAll();
		request.setAttribute("articleTypes", articleTypes);
		return rootPath+"public/spanMoreList";
	}
	
	/**
	 *更多资料，标签云出跳转
	 */
	@RequestMapping("resourceList")
	public String resourceList(HttpServletRequest request){
		List<ResourceFile> resourceFiles = resouceFileService.selectAll();
		request.setAttribute("resourceFiles", resourceFiles);
		return rootPath+"public/resourceList";
	}
	
	/**
	 *app下载
	 */
	@RequestMapping("appDownload")
	public String appDownload(@RequestParam("id") Integer id,HttpServletRequest request,HttpServletResponse response){
			AppVersion appVersion = appVersionService.selectByPrimaryKey(id);
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
				//设置输出长度
//		        response.setHeader("Content-Length", rf.getResourceSize()); 
		        String fileName ="windxun.apk";
		        response.reset();//清除response中的缓存信息
				InputStream inputStream;
				try {
				response.setHeader("Content-Disposition", "attachment;fileName="+new String(fileName.getBytes("utf-8"),"iso-8859-1"));
					inputStream = new ByteArrayInputStream(appVersion.getVersionContent());
					OutputStream os = response.getOutputStream();
					byte[] b = new byte[1024];
					int length;
					while ((length = inputStream.read(b)) > 0) {
						os.write(b, 0, length);
					}
					os.close();
					inputStream.close();
					appVersion.setVersionDownloadCount(appVersion.getVersionDownloadCount()+1);
					appVersion.setVersionContent(null);
					appVersion.setVersionDescription(null);
					appVersionService.updateByPrimaryKeySelective(appVersion);
					//下载记录
					AppVersionDownloadRecord record = new AppVersionDownloadRecord();
					final String ip = IPUtil.getIP(request);
					record.setVersionId(id);
					record.setCreateDate(new Date());
					record.setIp(ip);
					record.setVersionDownloadCount(1);
					appVersionDownloadRecordService.insertSelective(record);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		return null;
	}
	
	
}
